# _*_ coding:utf-8 _*_
from app import db
from . import admin
from flask import render_template, redirect, url_for, flash, session, request,jsonify,abort
from app.admin.forms import LoginForm, ManufacturerForm
from app.models import Admin, User, Manufacturer, TestLog, TestReview, Hardware
from sqlalchemy import or_
from functools import wraps
import os
import json
from decimal import *

from ..home.views import login_required

dir_server = os.path.dirname(os.path.realpath(__file__))
dir_results = os.path.abspath(os.path.join(dir_server, "../../results"))
dir_files = os.path.join(dir_server, 'files')


# 登录验证装饰器
def admin_login(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if session.get('admin'):  # 验证session
            return func(*args, **kwargs)
        else:
            return redirect(url_for('admin.login', next=request.url))

    return decorated_function


@admin.route('/')
def index():
    return "hello world！"


@admin.route("/manufacturer/list/", methods=["GET"])
# @admin_login
def manufacturer_list():
    """
    厂商列表
    """
    data = Manufacturer.query.all()
    return render_template("admin/manufacturer.html", data=data)  # 渲染模板


@admin.route('/manufacturer/add/', methods=["GET", "POST"])
# @admin_login
def manufacturer_add():
    if request.method == 'POST':
        manufacturer_name = request.form['name']
        contract_no = request.form['uuid']
        manufacturer = Manufacturer.query.filter_by(manufacturer_name=manufacturer_name).count()
        if manufacturer:
            flash("厂商已存在", "err")
            return redirect(url_for("admin.manufacturer_add"))
        data = Manufacturer(
            manufacturer_name=manufacturer_name,
            contract_no=contract_no
        )
        db.session.add(data)
        db.session.commit()
        return redirect(url_for("admin.manufacturer_list"))
    return render_template("admin/manufacturer_add.html")


@admin.route("/manufacturer/edit/<int:id>", methods=["GET","POST"])
# @admin_login
def manufacturer_edit(id=None):
    manufacturer = Manufacturer.query.get_or_404(id)
    form = ManufacturerForm()  # 实例化form表单
    if request.method == "GET":
        form.name.data = manufacturer.manufacturer_name
        form.uuid.data = manufacturer.contract_no
    elif request.method == 'POST':
        manufacturer.manufacturer_name = request.form.get("name")
        manufacturer.contract_no = request.form.get("uuid")
        db.session.add(manufacturer)  # 添加数据
        db.session.commit()  # 提交数据
        return redirect(url_for('admin.index'))  # 页面跳转

    return render_template("admin/manufacturer_edit.html", form=form)  # 渲染模板


@admin.route("/manufacturer/del/<int:id>/", methods=["GET"])
# @admin_login
def manufacturer_del(id=None):
    manufacturer = Manufacturer.query.get_or_404(id)  # 根据厂商id查找数据
    db.session.delete(manufacturer)             # 删除数据
    db.session.commit()                   # 提交数据
    return redirect(url_for('admin.index', page=1))  # 渲染模板


@admin.route('/results/<manu>/<host>')
def get_hardware(manu, host):
    """
    查询硬件信息
    """
    results = {}
    for manu in next(os.walk(dir_results))[1]:
        dir_manu = os.path.join(dir_results, manu)
        results[manu] = {}
        for host in next(os.walk(dir_manu))[1]:
            dir_host = os.path.join(dir_manu, host)
            results[manu][host] = next(os.walk(dir_host))[1]
    return render_template('host.html', results=results)


@admin.route('/results/<manu>/<host>/<oec_id>/<job>')
def get_job(manu, host, oec_id, job):
    """
    查询job信息
    """
    dir_job = os.path.join(dir_results, manu, host, oec_id, job)
    json_info = os.path.join(dir_job, 'compatibility.json')
    json_results = os.path.join(dir_job, 'factory.json')
    try:
        with open(json_info, 'r') as f:
            info = json.load(f)
            print(info)
        with open(json_results, 'r') as f:
            results = json.load(f)
            print(results)
    except Exception as e:
        abort(404)
    # return "job"
    return render_template('job.html', manu=manu, host=host, id=oec_id, job=job, info=info, results=results)


@admin.route('/results/<manu>/<host>/<oec_id>/<job>/logs/<name>')
def get_log(manu, host, oec_id, job, name):
    """
    查询用例日志
    """
    dir_job = os.path.join(dir_results, manu, host, oec_id, job)
    logpath = os.path.join(dir_job, name + '.log')
    if not os.path.exists(logpath):
        logpath = os.path.join(dir_job, 'job.log')
    try:
        with open(logpath, 'r') as f:
            log = f.read().split('\n')
    except Exception as e:
        abort(404)
    return render_template('log.html', name=name, log=log)


@admin.route('/admin/get_testreview/')
@admin_login
def get_testreview():
    datas = TestReview.query.all()
    return_datas = []
    for data in datas:
        hardware_name = Hardware.query.get(data.hardware_id).hardware
        return_data = {
            "testcase_name": data.testcase_name,
            # "test_result": data.test_result,
            "review_result": data.review_result,
            "review_comments": data.review_comments,
            "log_path": data.log_path,
            "hardware_name": hardware_name
        }
        return_datas.append(return_data)
    return jsonify({'data': return_datas})


@admin.route('/admin/query_testreview/', methods=['GET', 'POST'])
@admin_login
def query_testreview():
    if request.method == "GET":
        return_data = {}
        man_data = [i for i in Manufacturer.query.all()]
        for manufacturer in man_data:
            hardware = Manufacturer.query.get(manufacturer.id).hardware

            return_data[manufacturer.manufacturer_name] = [i.hardware for i in
                                                           hardware]
        return jsonify(return_data)
    if request.method == "POST":
        manufacturer_name = request.form.get("manufacturer_name")
        hardware = request.form.get("hardware")

        manufacture_obj = Manufacturer.query.filter(
            Manufacturer.manufacturer_name == manufacturer_name).first()

        hardware_obj = Hardware.query.filter(
            Hardware.manufacturer_id == manufacture_obj.id).filter(
            Hardware.hardware == hardware).first()

        testcase = TestReview.query.filter(
            TestReview.hardware_id == hardware_obj.id)

        return_datas = []

        for i in testcase:
            return_data = {
                "testcase_name": i.testcase_name,
                # "test_result": i.test_result,
                "review_result": i.review_result,
                "review_comments": i.review_comments,
                "log_path": i.log_path,
                "hardware_name": hardware_obj.hardware,
            }
            return_datas.append(return_data)
        return jsonify({"data": return_datas})


@admin.route('/admin/edit_testreview/<int:testcase_id>',
             methods=['GET', 'POST'])
@admin_login
def edit_testreview(testcase_id):
    data = TestReview.query.get(testcase_id)
    if request.method == "POST":
        review_result = request.form.get("review_result")
        review_comments = request.form.get("review_comments")
        data.review_result = review_result
        data.review_comments = review_comments
        db.session.commit()
        return jsonify({"msg": "ok"})
    hardware_name = Hardware.query.get(data.hardware_id).hardware
    return_data = {
        "testcase_name": data.testcase_name,
        # "test_result": data.test_result,
        "review_result": data.review_result,
        "review_comments": data.review_comments,
        "log_path": data.log_path,
        "hardware_name": hardware_name
    }
    return jsonify(return_data)


@admin.route('/admin/get_userinfo/')
def get_info():
    datas = User.query.all()
    return_datas = []
    for data in datas:
        return_data = {
            "username": data.username,
            "email": data.email,
            "contractnum": data.contractnum,
            "manufacturer": data.manufacturer
        }

        return_datas.append(return_data)
    return jsonify({"data": return_datas})


@admin.route('/admin/login/', methods=['GET', 'POST'])
def login():
    forms = LoginForm()  # 实例化forms
    if forms.validate_on_submit():  # 提交的时候进行验证,如果数据能被所有验证函数接受，则返回true，否则返回false
        data = forms.data  # 获取form数据信息（包含输入的用户名（account）和密码（pwd）等信息）,这里的account和pwd是在forms.py里定义的
        admin = Admin.query.filter_by(
            manager=data["manager"]).first()  # 查询表信息admin表里的用户名信息
        print(admin.password)
        if admin == None:
            flash("用户不存在")  # 操作提示信息，会在前端显示
            return redirect(url_for('admin.login'))
        elif admin != None and admin.password != data[
            "password"]:  # 这里的check_pwd函数在models 下Admin模型下定义
            flash("密码错误")
            return redirect(url_for('admin.login'))
        session['admin'] = data['manager']  # 匹配成功，添加session
        return redirect(
            request.args.get('next') or url_for('admin.index'))  # 重定向到首页
    return render_template('admin/login.html', form=forms)


@admin.route('/admin/logout/', methods=['GET', 'POST'])
def logout():
    session.pop('admin', None)
    return redirect(url_for('admin.login'))